<template>
  <div class="app-container">
    <!-- 患者信息表单 -->
    <div class="patient-info-form">
      <el-form :model="patientForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="患者姓名">
              <el-input v-model="patientForm.name" placeholder="患者姓名/手机号码/证件号码/卡号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="患者卡号">
              <el-input v-model="patientForm.cardNo" placeholder="请输入病人卡号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="患者年龄">
              <el-input v-model="patientForm.age" placeholder="请输入数字" style="width: calc(100% - 30px);" />
              <span style="margin-left: 10px;">岁</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出生日期">
              <el-date-picker v-model="patientForm.birthDate" type="date" placeholder="选择日期" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="性别">
              <el-select v-model="patientForm.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option label="男" value="0" />
                <el-option label="女" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="手机号码">
              <el-input v-model="patientForm.phone" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证件号码">
              <el-input v-model="patientForm.idCard" placeholder="请输入证件号码" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 药品部分 -->
    <div class="medicine-container">
      <div class="prescription-content">
        <!-- 左侧药品列表 -->
        <div class="prescription-left">
          <div class="rp-header">
            <span class="rp-title">药品列表</span>
          </div>
          <el-table :data="selectedMedicines" style="width: 100%">
            <el-table-column label="药品名称" prop="drugGenericName" />
            <el-table-column label="规格" prop="drugSpecification" />
            <el-table-column label="单位" prop="drugUnit" />
            <el-table-column label="单价" prop="retailPrice">
              <template #default="{ row }">
                {{ row.retailPrice }}元
              </template>
            </el-table-column>
            <el-table-column label="数量" width="150">
              <template #default="scope">
                <el-input-number v-model="scope.row.quantity" :min="1" size="small"
                  @change="handleQuantityChange(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="金额">
              <template #default="{ row }">
                {{ (row.retailPrice * (row.quantity || 1)).toFixed(2) }}元
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button type="danger" link @click="deleteMedicine(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="total-amount">
            总金额：{{ totalAmount }} 元
          </div>

          <div class="save-button-container">
            <el-button type="primary" :disabled="!selectedMedicines.length || !patientForm.name"
              @click="handleSave">保存</el-button>
          </div>
        </div>

        <!-- 右侧药品搜索和列表 -->
        <div class="prescription-right">
          <div class="search-header">
            <span>药品</span>
            <el-input v-model="searchForm.keyword" placeholder="输入药品中文或拼音搜索" clearable />
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>
          <el-table :data="medicineList" style="width: 100%" height="400">
            <el-table-column label="名称" prop="drugGenericName" />
            <el-table-column label="规格" prop="drugSpecification" width="100" />
            <el-table-column label="价格" prop="retailPrice">
              <template #default="{ row }">
                {{ row.retailPrice }}元
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button type="primary" size="small" @click="addMedicine(scope.row)">添加</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Shopping">
import { ref, reactive, computed } from 'vue'
import { listDrug } from "@/api/drug/drug"
import {addSaveData} from "@/api/shopping/shopping"
import { ElMessage } from 'element-plus'

// 患者信息表单数据
const patientForm = reactive({
  name: '',
  cardNo: '',
  age: '',
  birthDate: '',
  gender: '',
  phone: '',
  idCard: ''
})

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 药品列表
const medicineList = ref([])

// 已选药品列表
const selectedMedicines = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  drugGenericName: null,
})

/** 查询药品信息列表 */
function getDrugList() {
  listDrug(queryParams).then(response => {
    const tempList = []
    response.rows.forEach(item => {
      if (item.drugInventory > 0 && item.drugStatus == '启用') {
        tempList.push(item)
      }
    })
    medicineList.value = tempList
  })
}

// 搜索药品
const handleSearch = () => {
  queryParams.drugGenericName = searchForm.keyword
  getDrugList()
}

// 添加药品
const addMedicine = (item) => {
  const existingIndex = selectedMedicines.value.findIndex(medicine =>
    medicine.drugId === item.drugId && medicine.drugGenericName === item.drugGenericName
  )

  if (existingIndex !== -1) {
    const updatedMedicine = {
      ...selectedMedicines.value[existingIndex],
      quantity: (selectedMedicines.value[existingIndex].quantity || 1) + 1
    }
    selectedMedicines.value.splice(existingIndex, 1, updatedMedicine)
  } else {
    const newItem = {
      ...item,
      quantity: 1
    }
    selectedMedicines.value.push(newItem)
  }
}

// 修改数量
const handleQuantityChange = (row) => {
  const index = selectedMedicines.value.findIndex(item =>
    item.drugId === row.drugId && item.drugGenericName === row.drugGenericName
  )

  if (index !== -1) {
    const updatedMedicine = { ...selectedMedicines.value[index], quantity: row.quantity }
    selectedMedicines.value.splice(index, 1, updatedMedicine)
  }
}

// 删除药品
const deleteMedicine = (index) => {
  selectedMedicines.value.splice(index, 1)
}

// 计算总金额
const totalAmount = computed(() => {
  const medicineAmount = selectedMedicines.value.reduce((sum, medicine) => {
    return sum + (Number(medicine.retailPrice) * Number(medicine.quantity || 1))
  }, 0)
  return medicineAmount.toFixed(2)
})

// 添加保存方法
const handleSave = () => {
  // if (!patientForm.name) {
  //   proxy.$modal.msgError("请先填写患者信息");
  //   return;
  // }
  // if (!selectedMedicines.length) {
  //   proxy.$modal.msgError("请先添加药品");
  //   return;
  // }
  const saveData = {
    patientInfo: {
      name: patientForm.name,
      cardNumber: patientForm.cardNo,
      age: patientForm.age,
      birthDate: patientForm.birthDate,
      gender: patientForm.gender,
      phone: patientForm.phone,
      idCard: patientForm.idCard
    },
    medicines: selectedMedicines.value,
    totalAmount: totalAmount.value
  };
  console.log('保存的数据:', saveData);
  
  addSaveData(saveData).then(response => {
    if (response.code == 200) {
      ElMessage.success("本次一共消费"+response.data+"元")
    }else{
      ElMessage.error('保存失败')
    }
  })

  // 这里调用保存API
  // proxy.$modal.msgSuccess("保存成功");
  // 清空表单和已选药品
  // patientForm.value = {
  //   name: '',
  //   cardNo: '',
  //   age: '',
  //   birthDate: '',
  //   gender: '',
  //   phone: '',
  //   idCard: ''
  // };
  // selectedMedicines.value = [];
};

// 页面加载时获取药品列表
onMounted(() => {
  getDrugList()
})
</script>

<style scoped>
.patient-info-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.medicine-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.prescription-content {
  display: flex;
  gap: 20px;
}

.prescription-left {
  flex: 0 0 60%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
}

.prescription-right {
  flex: 0 0 calc(40% - 20px);
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
}

.rp-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.rp-title {
  font-size: 16px;
  font-weight: bold;
}

.search-header {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-header .el-input {
  flex: 1;
}

.fee-info {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #dcdfe6;
  display: flex;
  justify-content: flex-end;
  font-size: 16px;
  font-weight: bold;
}

.save-button-container {
  margin-top: 20px;
  text-align: right;
  padding: 16px;
  border-top: 1px solid #EBEEF5;
}

.total-amount {
  margin-top: 16px;
  text-align: right;
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
  padding-right: 16px;
}
</style>
